import java.util.HashMap;

/**
 * Map应用
 * https://leetcode.cn/problems/contains-duplicate-ii/description/
 * 可能存在多个重复元素，需要map重新put更新value值，如果后面又出现了重复的元素，
 * 和最近的下标作差看是否<=k
 */
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer,Integer> map = new HashMap<>();
        boolean flg = true;
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i],i);
            }else {
                if (Math.abs(i-map.get(nums[i])) <= k) {
                    return true;
                }else {
                    map.put(nums[i],i);
                }
            }
        }
        return false;
    }
}